"""
客服常用语配置
"""
import logging

from django.db.models import Q

from biz.const import Role, TempType
from biz.core.thanos.models import Phrase
from biz.exceptions import ERROR_DATA_NOT_EXISTS, ERROR_KEFU_UPDATE_PUBLIC_PHRASE
from gis.common.django_ext.models import paginate
from gis.common.exceptions import BizException

_LOGGER = logging.getLogger(__name__)


def list_phrase(user, page_no, page_size, type_id=None):
    assert page_no > 0
    assert page_size > 0
    assert user.get('pro_id')
    assert user.get('role_id')
    query = Phrase.objects.filter(pro_id=user['pro_id']).all()
    if type_id:
        query = query.filter(type_id=type_id)
    # 客服只能可以看到自己配置的 + 公用模版
    if user['role_id'] == Role.KEFU:
        query = query.filter(Q(user_id=user['id']) | Q(user_id__isnull=True))
    return query.count(), [e.to_dict() for e in paginate(query.order_by('-created_at'), page_no, page_size)]


def add_phrase(user, type_id, temp_type, title, context):
    assert user.get('pro_id')
    data = Phrase.objects.create(type_id=type_id, temp_type=temp_type, title=title, context=context,
                                 pro_id=user['pro_id'])
    if temp_type == TempType.PRIVATE:
        data.user_id = user['id']
        data.save()
    return data.to_dict()


def get_phrase(data_id):
    data = _get_data(data_id)
    return data.to_dict()


def update_phrase(data_id, user, title, context):
    data = _get_data(data_id)
    assert user.get('role_id')
    if data.temp_type == TempType.PUBLIC and user['role_id'] == Role.KEFU:
        raise BizException(ERROR_KEFU_UPDATE_PUBLIC_PHRASE)
    data.title = title
    data.context = context
    data.save()
    return data.to_dict()


def delete_phrase(data_id, user):
    assert data_id
    assert user.get('role_id')
    data = _get_data(data_id)
    if data.temp_type == TempType.PUBLIC and user['role_id'] == Role.KEFU:
        raise BizException(ERROR_KEFU_UPDATE_PUBLIC_PHRASE)
    data.delete()


def list_customer_phrase(user, type_id):
    assert user.get('pro_id')
    assert user.get('role_id')
    query = Phrase.objects.filter(pro_id=user['pro_id']).all()
    if type_id:
        query = query.filter(type_id=type_id)
    # 客服只能可以看到自己配置的 + 公用模版
    if user['role_id'] == Role.KEFU:
        query = query.filter(Q(user_id=user['id']) | Q(user_id__isnull=True))
    # 公用模版
    pub_list = [e.to_dict() for e in query.filter(temp_type=TempType.PUBLIC).order_by('-created_at')]
    pri_list = [e.to_dict() for e in query.filter(temp_type=TempType.PRIVATE).order_by('-created_at')]
    return pub_list, pri_list


def _get_data(data_id):
    assert data_id > 0
    data = Phrase.objects.filter(pk=data_id).first()
    if not data:
        raise BizException(ERROR_DATA_NOT_EXISTS)
    return data
